package com.yf.modules.security.handler;

import cn.hutool.core.util.StrUtil;
import com.yf.configuration.SecurityProperties;
import com.yf.modules.security.service.OnlineUserService;
import com.yf.modules.security.service.TokenProvider;
import com.yf.modules.security.model.dto.OnlineUserDto;
import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;

/**
 * @author chentianwei
 * @date 2023/4/26 9:49
 * @description Jwt过滤器
 */
@Component
public class JwtFilter extends OncePerRequestFilter {

    private static final Logger log = LoggerFactory.getLogger(JwtFilter.class);

    private final TokenProvider tokenProvider;
    private final OnlineUserService onlineUserService;
    private final SecurityProperties properties;

    public JwtFilter(TokenProvider tokenProvider,
                     OnlineUserService onlineUserService,
                     SecurityProperties properties) {
        this.tokenProvider = tokenProvider;
        this.onlineUserService = onlineUserService;
        this.properties = properties;
    }

    /**
     * 初步检测Token
     *
     * @param request /
     * @return /
     */
    private String resolveToken(HttpServletRequest request) {
        String bearerToken = request.getHeader(properties.getHeader());
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(properties.getTokenStartWith())) {
            // 去掉令牌前缀
            return bearerToken.replace(properties.getTokenStartWith(), "");
        } else {
            log.debug("非法Token：{}", bearerToken);
        }
        return null;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = resolveToken(request);
        //1.token不为空的去查redis表信息
        if (StrUtil.isNotEmpty(token)) {
            OnlineUserDto onlineUserDto = null;
            boolean needCleanUserCache = false;
            try {
                //先尝试从缓存中获得用户信息
                onlineUserDto = onlineUserService.getOne(properties.getOnlineKey() + token);
            } catch (ExpiredJwtException e) {
                needCleanUserCache = true;
            } finally {
                //如果拿不到信息的，要将缓存信息清除
                if (needCleanUserCache || Objects.isNull(onlineUserDto)) {
                    onlineUserService.cleanUserCache(String.valueOf(tokenProvider.getClaims(token).get(TokenProvider.AUTHORITIES_KEY)));
                }
            }
            if (onlineUserDto != null && StringUtils.hasText(token)) {
                //如果信息正常存在，保存鉴权信息，同时如果token已经有的，要对时间进行续期
                Authentication authentication = tokenProvider.getAuthentication(token);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                //Token过期时间更新
                tokenProvider.checkRenewal(token);
            }

        }
        filterChain.doFilter(request, response);
    }
}
